# 记录用户操作

util = require('./util')
config = require('../config')

mongoose = config.mongoose
Schema = config.Schema


exports.user_id_type_portal = user_id_type_portal = 0
exports.user_id_type_trade = user_id_type_trade = 1

UserOperationSchema = new Schema
  id:
    type:String
    required:true
  id_type:
    type: Number
    required: true
  title:
    type: String
    required: true
  description:
    type:String
    required: true
  result:
    type:Boolean
    required: true
  error_info:
    type:String
    default: ""
  created_on:
    type:Date
    default: new Date()

UserOperationSchema.set('autoIndex',false)
UserOperationSchema.index({id:1,id_type:1})
UserOperationSchema.index({id:1,id_type:1,title:1})
UserOperationSchema.index({id:1,id_type:1,result:1})
UserOperationSchema.index({id:1,id_type:1,created_on:1})

UserOperationSchema.statics.search = search = (id,title,result,begin_date,end_date,page_num,page_size,cb) ->
  criteria = {id,id_type:user_id_type_trade}
  unless result in [null,undefined]
    criteria.result = result
  unless title in [null,undefined]
    criteria.title = title
  unless begin_date in [null,undefined] or end_date in [null,undefined]
    criteria.created_on = {$gte: begin_date, $lte: end_date}
  util.pagination_find UserOperation,criteria,{created_on:-1},page_num,page_size,cb
  


UserOperationSchema.statics.find_by_trade_id = (id, page_num,page_size, cb) ->
  search id,null,null,null,null,page_num,page_size,cb

UserOperationSchema.statics.find_by_title = (id,title, page_num,page_size, cb) ->
  search id,title,null,null,null,page_num,page_size,cb

UserOperationSchema.statics.find_by_result = (id,result, page_num,page_size, cb) ->
  search id,null,result,null,null,page_num,page_size,cb

UserOperationSchema.statics.find_by_time = (id,begin_date,end_date, page_num,page_size, cb) ->
  search id,null,null,begin_date,end_date,page_num,page_size,cb

UserOperationSchema.statics.remove_by_trade_id = (id,cb) ->
  UserOperation.remove {id:id,id_type:user_id_type_trade}, cb

UserOperationSchema.statics.record_trade_user_op = (id,title,description,result,error_info,cb) ->
  new UserOperation({id,id_type:user_id_type_trade, title,description,result,error_info,created_on:new Date()}).save cb

UserOperation = mongoose.model("UserOperation",UserOperationSchema)

exports.UserOperation = UserOperation

